/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cenluan.session;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.cenluan.common.Const;
import com.cenluan.user.User;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.render.JavascriptRender;
import com.jfinal.render.JsonRender;
import com.jfinal.render.Render;
import com.jfinal.render.TextRender;

/**
 * session转视图拦截器，手动把session里的一些数据放入request，使视图中可以操作
 * 
 * @author peak
 * 
 */
public class SessionInViewInterceptor implements Interceptor {

	public void intercept(ActionInvocation ai) {
		ai.invoke();
		Controller controller = ai.getController();
		Render render = controller.getRender();
		// 如果渲染的是json，text或者javascript，不要把session数据带入视图
		if (render instanceof JsonRender || render instanceof TextRender
				|| render instanceof JavascriptRender) {
			return;
		}
		HttpSession session = controller.getSession();
		if (session == null) {
			return;
		}
		Map<String, Object> sessionMap = new HashMap<String, Object>();
		controller.setAttr("session", sessionMap);
		Enumeration<String> names = session.getAttributeNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			sessionMap.put(name, session.getAttribute(name));
		}
		// 把session里的user一些属于设置进去，为了视图层方便判定
		User user = controller.getSessionAttr(Const.SESSION_USER);
		controller.setAttr("admin",
				user != null && User.ROLE_ADMIN.equals(user.getStr("role")));

	}

}
